package br.com.visagio.aulabigdata.util;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import twitter4j.HashtagEntity;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.RateLimitStatus;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import br.com.visagio.aulabigdata.business.TwitterBusiness;

public class TwitterUtil {
	
	public static final String HASHTAG = "#eleicoes2014";
	public static long lastTweetId = 0;
	static Logger logger = LoggerFactory.getLogger(TwitterUtil.class);
	
	public static List<Status> getTweetsByHashtag(String hashtag) throws TwitterException {  
	    Twitter twitter = TwitterFactory.getSingleton();
	    Query q = new Query(hashtag);
	    q.setCount(100);
	    q.setSince("2014-01-01");
	    q.setSinceId(lastTweetId);

		QueryResult tweets = twitter.search(q);
		lastTweetId = tweets.getMaxId();
		
		return tweets.getTweets();
	}  
	
	public static boolean hasReachedSearchLimit(int nRetrieved){
		Twitter twitter = TwitterFactory.getSingleton();
		try {
			Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus();
			RateLimitStatus searchLimitStatus = rateLimitStatus.get("/users/search");
			if(nRetrieved < 30){
				return searchLimitStatus.getRemaining() == 1;
			}
			return searchLimitStatus.getRemaining() == 30;
		} catch (TwitterException e) {
			logger.error("Erro ao checar a limite do Twitter");
			return true;
		}
	}
	
	public static String[] getHashtagArray(HashtagEntity[] hashtagEntities) {
		String[] hashtags = new String[hashtagEntities.length];
		for(int i = 0; i<hashtagEntities.length; i++){
			hashtags[i] = hashtagEntities[i].getText();
		}
			
		return hashtags;
	}
	
	public static void main(String[] args) throws TwitterException, ParseException {
		TwitterBusiness twitterBusiness = new TwitterBusiness();
		//twitterBusiness.removeAllTweets(DBUtil.COLLECTION);
		twitterBusiness.searchAndSaveLatestTweets();
		//getTweetsByHashtag(HASHTAG);
	}
}
